import { useContext,createContext, useReducer, useEffect } from 'react'
import listReducer from '../Reducer/list-reducer';

const ListContext = createContext();

export const useList = () => useContext(ListContext);

const initState = {//多个状态
    list:[],
    loading:false,
}

const ListProvider = ({children}) => {
    const [state,dispatch] = useReducer(listReducer,initState);
    const {loading} = state
  
    useEffect(()=>{
      //dispatch更新状态
      dispatch({type:'set_loading',loading:true})
      setTimeout(()=>{
          const list = [
              {id:1,title:'aaaaaa'},
              {id:2,title:'bbbbbb'},
              {id:3,title:'cccccc'},
          ]
          dispatch({type:'set_list',list})
          dispatch({type:'set_loading',loading:false})
      },2000)
    },[])
  
    if(loading){
      return <div>loading...</div>
    }

  return (
    <ListContext.Provider value={{state, dispatch}}>
        {children}
    </ListContext.Provider>
  )
}

export default ListProvider